import React, { useEffect, useState } from "react";
import { Modal, Form, Row, Col, InputNumber, Space, Button, Input } from "antd";
import { modalPropsType } from "@/constants/types";
import "./index.less";
import XlSelect from "@/components/Form/XlSelect";
import { useModel } from "@umijs/max";
import { billDetail } from "../../services";

const { Item } = Form;
const rules = [{required: true, message: '此项必填'}];
const initValues = {feeItems: [{isDefault: true}]};
const disabledFee = ["coupon"];

const BillUpdate = ({visible, onCancel, onSubmit, title, loading, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  const feeItems = Form.useWatch("feeItems", form);
  const [lastDefaultIndex, setLastDefaultIndex] = useState<number>(0);
  const {getDict} = useModel("dictModel");
  const feeItemMaps = getDict("feeItem");
  const units = getDict("unit");


  const search = async () => {
    const res = await billDetail({id: currentRow?.id});
    form.setFieldsValue({
      feeItems: res?.feeItems?.map((v: any) => ({
        ...v,
        isDefault: true
      }))
    });
  }

  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      id: currentRow?.id,
      feeItems: res?.feeItems?.map((v: any) => ({
        ...v,
        isDefault: undefined,
        feeName: feeItemMaps?.find((fee: any) => fee?.value === v?.feeCode)?.label
      }))
    });
  }


  const totalAmount = feeItems?.reduce((p: number, v: any) => {
    return p + Number(+(v?.price || 0) * +(v?.num || 0));
  }, 0);

  useEffect(() => {
    if (currentRow?.id) {
      search();
    }
  }, [currentRow?.id]);


  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      maskClosable={false}
      width="1400px"
    >
      <Form form={form} className="modal-form-padding" initialValues={initValues}>
        <div className="xl-self-table">
          <div className="thead">
            <Row className="tr">
              <Col span={5}>
                <div className="th">费用项</div>
              </Col>
              <Col span={6}>
                <div className="th">计费数量(KG/CBM)</div>
              </Col>
              <Col span={5}>
                <div className="th">单价</div>
              </Col>
              <Col span={4}>
                <div className="th">费用/元</div>
              </Col>
              <Col span={4}>
                <div className="th">操作</div>
              </Col>
            </Row>
          </div>
          <div className="tbody">
            <Form.List name="feeItems">
              {(fields, { add, remove }) => (
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  {fields.map((field, fieldIndex) => (
                    <Row className="tr" key={field.name}>
                      {/* <Item noStyle hidden name={[field.name, 'feeCode']}>
                        <Input />
                      </Item> */}
                      <Col span={5}>
                        <div className="td">
                          <Item noStyle shouldUpdate>
                            {({getFieldValue}) => {
                              const curr = getFieldValue(["feeItems", field.name]);
                              return (
                                <Item style={{marginBottom: 0}} name={[field.name, 'feeCode']} rules={rules}>
                                  <XlSelect options={feeItemMaps} disabled={curr.isDefault || disabledFee.includes(curr.feeCode)} optionFilterProp="label" showSearch allowClear style={{width: 200}} />
                                </Item>
                              );
                            }}
                          </Item>
                        </div>
                      </Col>
                      <Col span={6}>
                        <div className="td">
                          <Item noStyle shouldUpdate>
                            {({getFieldValue}) => {
                              const curr = getFieldValue(["feeItems", field.name]);
                              // const editable = EDIT_FEE.includes(curr?.feeCode);

                              return (
                                <Space>
                                  <Item style={{marginBottom: 0}} name={[field.name, 'num']} rules={rules}>
                                    <InputNumber disabled={disabledFee.includes(curr.feeCode)} min={0} style={{width: 180}} />
                                  </Item>
                                  <Item style={{marginBottom: 0}} name={[field.name, 'unit']} rules={rules}>
                                    <XlSelect disabled={disabledFee.includes(curr.feeCode)} options={[...units, {label: '票', value: '票'}]} style={{width: 120}} />
                                  </Item>
                                </Space>
                              );
                            }}
                          </Item>
                        </div>
                      </Col>
                      <Col span={5}>
                        <div className="td">
                          <Item noStyle shouldUpdate>
                            {({getFieldValue}) => {
                              const curr = getFieldValue(["feeItems", field.name]);
                              // const editable = EDIT_FEE.includes(curr?.feeCode);

                              return (
                                <Item name={[field.name, 'price']} rules={rules} style={{marginBottom: 0}}>
                                  <InputNumber disabled={disabledFee.includes(curr.feeCode)} min={0} style={{width: 200}} />
                                </Item>
                              );
                            }}
                          </Item>
                        </div>
                      </Col>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle shouldUpdate>
                            {({getFieldValue}) => {
                              const curr = getFieldValue(["feeItems", field.name]);
                              const value = Number(+(curr?.price || 0) * +(curr?.num || 0)).toFixed(2);

                              return (
                               <strong>{value}</strong>
                              );
                            }}
                          </Item>
                        </div>
                      </Col>
                      <Col span={4}>
                        <div className="td">
                          <Item noStyle shouldUpdate>
                            {({getFieldValue}) => {
                              const curr = getFieldValue(["feeItems", field.name]);
                              return (
                                <Space>
                                  {lastDefaultIndex === fieldIndex && <Button type="link" onClick={() => add({isDefault: false})}>新增</Button>}
                                  {(fieldIndex > 0) && !disabledFee.includes(curr?.feeCode) && <Button type="link" danger onClick={() => remove(field.name)}>删除</Button>}
                                </Space>
                              );
                            }}
                          </Item>
                        </div>
                      </Col>
                    </Row>
                  ))}
                </div>
              )}
            </Form.List>
          </div>
          <div className="tfooter">
            <Row className="tr">
              <Col span={5}><div className="td"><strong>总计费用</strong></div></Col>
              <Col span={6}><div className="td"></div></Col>
              <Col span={5}><div className="td"></div></Col>
              <Col span={4}><div className="td"><strong>{Number(totalAmount).toFixed(2)}</strong></div></Col>
              <Col span={4}><div className="td"></div></Col>
            </Row>
          </div>
        </div>
      </Form>
    </Modal>
  );
}
export default BillUpdate;